package com.dubbo.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Description
 * @Author xsd
 */
@Slf4j
public class RedisUtil {

    private static final Charset DEFAULT_CHARSET;
    private static final StringRedisSerializer STRING_SERIALIZER;
    private static final JdkSerializationRedisSerializer OBJECT_SERIALIZER;
    private RedisTemplate<String, Object> redisTemplate;

    public RedisUtil(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.redisTemplate.setKeySerializer(STRING_SERIALIZER);
        this.redisTemplate.setValueSerializer(OBJECT_SERIALIZER);
    }

    /**
     * 获取值
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object resultStr = this.redisTemplate.execute((RedisCallback<Object>) (connection) -> {
            RedisSerializer<String> serializer = this.getRedisSerializer();
            byte[] keys = serializer.serialize(key);
            byte[] values = connection.get(keys);
            return OBJECT_SERIALIZER.deserialize(values);
        });
        log.info("[redisTemplate redis]取出 缓存  url:{} ", key);
        return resultStr;
    }

    /**
     * 设置值-过期时间
     * @param key
     * @param value
     * @param time
     */
    public void setExpire(final String key, final Object value, final long time) {
        this.redisTemplate.execute((RedisCallback<Long>) (connection) -> {
            RedisSerializer<String> serializer = this.getRedisSerializer();
            byte[] keys = serializer.serialize(key);
            byte[] values = OBJECT_SERIALIZER.serialize(value);
            connection.setEx(keys, time, values);
            return 1L;
        });
    }

    private RedisSerializer<String> getRedisSerializer() {
        return this.redisTemplate.getStringSerializer();
    }

    static {
        DEFAULT_CHARSET = StandardCharsets.UTF_8;
        STRING_SERIALIZER = new StringRedisSerializer();
        OBJECT_SERIALIZER = new JdkSerializationRedisSerializer();
    }
}
